#!/usr/bin/python
import httplib
import sys
from string import maketrans
import json

HOST = "translate.yandex.net"
RSRC = "/api/v1.5/tr.json/translate?key=trnsl.1.1.20130425T160404Z.4f344a254ad6a151.f0955220dc790bd3b962636fd0c468f22d718558&lang=ru"
HTTP_OK = 200
TRANS_OK = 200

def outResult(uData):
 result = uData.encode("utf8")
 return result

def readFromStdIn():
 result = ""
 for line in sys.stdin:
  result += "&text=" + line.strip()
 return result

def prepareURL(arg):
 text = arg.strip()
 transTable = maketrans(" ?", "+.")
 text = text.translate(transTable)
 return text

def parseJSONResponseToList(dataString):
 respDict = json.loads(dataString)
 transCode = respDict['code']
 if transCode == TRANS_OK:
  lineList = respDict['text']
 else:
  lineList = None
 return lineList


def getResponse(host, rsrc):
 h = httplib.HTTPSConnection(host)
 h.putrequest("GET", rsrc)
 h.putheader("Host", host)
 h.putheader("User-agetnt", "python httplib on linux 3")
 h.endheaders()
 response = h.getresponse()
 retCode = response.status
 retMsg = response.msg
 headers = response.getheaders()
 if retCode == HTTP_OK:
  line = response.read()
  return line
 else:
  print retCode, headers, retMsg

#prepare translate

respLine = getResponse(HOST, RSRC + prepareURL(readFromStdIn()))
transLines = parseJSONResponseToList(respLine)
translation = u''
for line in transLines:
 translation += line + ' '
try:
 outLine = outResult(translation)
except:
 pass
print outLine
